//
//  KKImageItemsViewController.m
//  KKImagePickerController
//
//  Created by Mac mini on 16/1/21.
//  Copyright © 2016年 JuniorCodingPerson. All rights reserved.
//

#import "KKImageItemsViewController.h"

#import "KKImagePickerManager+Tools.h"
#import "KKImageLibraryManager.h"
#import "KKImagePickerModel.h"

#pragma mark - KKImageItemsViewFooterView methods

@interface KKImageItemsViewFooterView : UICollectionReusableView

@property (nonatomic, strong) UILabel *kk_titleLabel;

@end

@implementation KKImageItemsViewFooterView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: CGRectMake(0, 0, CGRectGetWidth([[UIScreen mainScreen] bounds]), CGRectGetHeight(frame))];
    if (self) {
        
        _kk_titleLabel = [[UILabel alloc] initWithFrame: CGRectMake(0, CGRectGetHeight(self.bounds) - 30, CGRectGetWidth(self.bounds), 20)];
        _kk_titleLabel.textAlignment = NSTextAlignmentCenter;
        _kk_titleLabel.textColor = [UIColor lightGrayColor];
        _kk_titleLabel.font = [UIFont systemFontOfSize: 16];
        [self addSubview: _kk_titleLabel];
    }
    return self;
}

@end

#pragma mark - KKImageItemsViewController methods

@interface KKImageItemsViewCell : UICollectionViewCell

@property (nonatomic, readonly) UIImageView* itemImageView;
@property (nonatomic, readonly) UIImageView *choosedImageView;
@property (nonatomic, readonly) UIView *choosedView;
@property (nonatomic) BOOL kk_selected;

@property (nonatomic, strong) KKImageItem *imageItem;

@end

@implementation KKImageItemsViewCell

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: frame];
    if (self) {
        
        UIView* contentView = [self contentView];
        
        _itemImageView = [[UIImageView alloc] initWithFrame: [self bounds]];
        _itemImageView.contentMode = UIViewContentModeScaleAspectFill;
        _itemImageView.clipsToBounds = YES;
        [contentView addSubview: _itemImageView];
        
        _choosedImageView = [[UIImageView alloc] initWithFrame: CGRectMake(CGRectGetWidth(contentView.bounds) - 28, 4, 24, 24)];
        
        NSString *imagePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"KKImagePickerController.bundle/Images/kk_item_seleted@2x.png"];
        
        _choosedImageView.image = [UIImage imageWithContentsOfFile: imagePath];
        _choosedImageView.hidden = YES;
        [contentView addSubview: _choosedImageView];
        
        _choosedView = [[UIView alloc] initWithFrame: [self bounds]];
        _choosedView.backgroundColor = [UIColor colorWithWhite: 0.0 alpha: 0.5];
        _choosedView.hidden = true;
        [contentView addSubview: _choosedView];
    }
    return self;
}

- (void)setKk_selected:(BOOL)kk_selected {
    
    _choosedImageView.hidden = !kk_selected;
    _choosedView.hidden = !kk_selected;
}

- (void)setImageItem:(KKImageItem *)imageItem {
    if (_imageItem != imageItem) {
        _imageItem = imageItem;
        
        if (_imageItem.thumbImage != nil) {
            self.itemImageView.image = _imageItem.thumbImage;
        }
        else {
            CGSize imageSize = CGSizeMake(CGRectGetWidth(self.itemImageView.bounds) * [UIScreen mainScreen].scale, CGRectGetHeight(self.itemImageView.bounds) * [UIScreen mainScreen].scale);
            PHAsset* asset = _imageItem.asset_8;
            PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
            options.resizeMode = PHImageRequestOptionsResizeModeExact;
            options.synchronous = YES;
            __weak UIImageView *weakImageView = self.itemImageView;
            __weak typeof(self) weakSelf = self;
            [[PHImageManager defaultManager] requestImageForAsset: asset targetSize: imageSize contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                weakImageView.image = result;
                weakSelf.imageItem.thumbImage = result;
            }];
        }
        self.kk_selected = [[KKImagePickerSet pickerSet] kk_matchItem: _imageItem];
    }
}

@end

#pragma mark - KKImageItemsViewController methods

static NSString* KKImageItemCollectionCellIdentifier = @"KKImageItemCollectionCellIdentifier";
static NSString* KKImageItemCollectionFooterIdentifier = @"KKImageItemCollectionFooterIdentifier";

@interface KKImageItemsViewController () {
    
    CGSize _itemCellSize;
}

@property (nonatomic, strong) NSArray *kk_assetItems;

@end

@implementation KKImageItemsViewController

+ (KKImageItemsViewController *)itemsViewController {
    
    UICollectionViewFlowLayout *flowLayout = [UICollectionViewFlowLayout new];
    KKImageItemsViewController *viewController = [[KKImageItemsViewController alloc] initWithCollectionViewLayout: flowLayout];
    return viewController;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    CGFloat width = CGRectGetWidth(self.collectionView.bounds);
    CGFloat itemWidth = (width - 4 * 5) / 4.0;
    
    _itemCellSize = CGSizeMake(itemWidth, itemWidth);
    
    // Register cell classes
    [self.collectionView registerClass:[KKImageItemsViewCell class] forCellWithReuseIdentifier: KKImageItemCollectionCellIdentifier];
    [self.collectionView registerClass: [KKImageItemsViewFooterView class] forSupplementaryViewOfKind: UICollectionElementKindSectionFooter withReuseIdentifier: KKImageItemCollectionFooterIdentifier];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    [self kk_loadAllItemsData];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style: UIBarButtonItemStylePlain target: self action: @selector(kk_save)];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.navigationItem.title = self.kk_groupItem.kk_groupName;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear: animated];
    
    [self.navigationController setToolbarHidden: false animated: true];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear: animated];
    
    [self.navigationController setToolbarHidden: true animated: true];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private methods

- (void)kk_loadAllItemsData {
    
    __weak UICollectionView *weakCollectionView = self.collectionView;
    
    __weak typeof(self) weakSelf = self;
    [[KKImageLibraryManager kk_defaultManager] kk_searchAllItemsFromLibraryWithGroup:_kk_groupItem.kk_assetCollection result:^(NSArray *items) {
        weakSelf.kk_assetItems = [NSArray arrayWithArray: items];
        [weakCollectionView reloadData];
    }];
}

- (void)kk_save {
    
    [[NSNotificationCenter defaultCenter] postNotificationName: KKImagePickerDismissNotificationName object: nil];
}


#pragma mark <UICollectionViewDataSource>

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return _kk_assetItems.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return _itemCellSize;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeMake(CGRectGetWidth(collectionView.bounds), 40);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(4, 4, 4, 4);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 4.0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 4.0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    KKImageItemsViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier: KKImageItemCollectionCellIdentifier forIndexPath: indexPath];
    
    // Configure the cell
    cell.imageItem = _kk_assetItems[indexPath.row];
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    KKImageItemsViewFooterView *footerView = nil;
    
    if ([kind isEqualToString: UICollectionElementKindSectionFooter ]){
        
        footerView = (KKImageItemsViewFooterView*)[collectionView dequeueReusableSupplementaryViewOfKind :kind   withReuseIdentifier: KKImageItemCollectionFooterIdentifier forIndexPath:indexPath];
        
        footerView.kk_titleLabel.text = [NSString stringWithFormat: @"共%@张照片", @(_kk_assetItems.count)];
    }
    return footerView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    KKImageItem* assetItem = _kk_assetItems[indexPath.row];
    
    KKImagePickerSet *pickerSet = [KKImagePickerSet pickerSet];
    [pickerSet kk_setItem: assetItem];
    
    [collectionView reloadItemsAtIndexPaths: @[indexPath]];
    
    NSInteger count = [[pickerSet kk_selectedItems] count];
    
    NSString *title = nil;
    if (pickerSet.kk_maxLimit == 0) {
        title = [NSString stringWithFormat: @"保存(%@)", @(count)];
    }
    else {
        title = [NSString stringWithFormat: @"保存(%@/%@)", @(count),@(pickerSet.kk_maxLimit)];
    }
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle: count == 0 ?@"保存":title style: UIBarButtonItemStylePlain target: self action: @selector(kk_save)];
    self.navigationItem.rightBarButtonItem = rightItem;
}

@end
